package com.chidopi.market.aa.security;

import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;

import com.chidopi.market.aa.domain.Roles;
import com.chidopi.market.aa.domain.UserDetailsImpl;

public class CustomAccessDecisionManager implements AccessDecisionManager{
	
	private static Logger logger = LoggerFactory.getLogger(CustomAccessDecisionManager.class);
	
	@Override
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
			
		Object obj = authentication.getPrincipal();
		logger.info("getPrincipal: " + obj);
		if( obj instanceof UserDetailsImpl){
			UserDetailsImpl userDetails = (UserDetailsImpl) obj;
			List<Roles> roles = userDetails.getAccount().getRoles();
			if(logger.isDebugEnabled()){
				logger.debug("roles: " + roles);
				logger.debug("URL: " + object.toString());  //object is a URL.
				logger.debug("ConfigAttributes: " + configAttributes);
			}
			for(Roles role: roles){
				String rolename =  role.getRolename();
				SecurityConfig sc = new SecurityConfig(rolename);
				
				if(configAttributes.contains(sc)){
					if(logger.isDebugEnabled()){
						logger.debug(rolename + " Allowed Access "+ object);
					}
					return;
				}
			}
			throw new AccessDeniedException("no right"); 
		}		
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
